import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

import $store from '../store'
import routes from './route'

import Layout from '../layout/Layout.vue'
import FullLayout from '../layout/FullLayout.vue'
const router = createRouter({
    history: createWebHashHistory(),
    routes : [
        {
            path : '/',
            component : FullLayout,
            meta : {title : '首页', noLogin : true, full : true},
            beforeEnter(to, from, next) {
                if($store.state.login.auth) {
                    next({path : '/account'})
                }else {
                    next()
                }
            },
            children : [
                {
                    path : '',
                    component : () => import('@/pages/home/index.vue')
                }
            ]
        },

        {
            path : '/about',
            name : 'about',
            meta : {title : '关于我们', noLogin : true, full : true},
            component : FullLayout,
            children : [
                {
                    path : '',
                    component : () => import('@/pages/about/index.vue')
                }
            ]
        },

        {
            path : '/login',
            name : 'login',
            meta : {title : '登录', noLogin : true, hidden : true},
            component : Layout,
            children : [
                {
                    path : '',
                    component : () => import('@/pages/login/login.vue')
                }
            ]
        },

        {
            path : '/forget',
            name : 'forget',
            meta : {title : '找回密码', noLogin : true, hidden : true},
            component : Layout,
            children : [
                {
                    path : '',
                    component : () => import('@/pages/login/forget.vue')
                }
            ]
        },
    
        {
            path : '/register',
            name : 'register',
            meta : {title : '注册', noLogin : true, hidden : true},
            component : Layout,
            children : [
                {
                    path : '',
                    component : () => import('@/pages/login/register.vue')
                }
            ]
        },

        ...routes,
    ]
})

router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    if(!to.meta.noLogin && !$store.state.login.auth) {
        next({path : '/login', query : {redirect : encodeURIComponent(to.fullPath)}})
        return
    }
    next()
})

export default router